import * as fs from "fs";
import { IGameConfig } from "./IGame";
/**
 * ConfigManager继承自IGameConfig 
 * IGameConfig由程序自动生成 
 * @example
 * memo: IMemo[] = [];
 * sheetName:sheetInterface[] = [];
 */
class ConfigManager extends IGameConfig {
    private static _ins: ConfigManager;
    public static get Ins() {
        return this._ins = this._ins ? this._ins : new ConfigManager();
    }
    /**
     * 将json数据初始化 赋值到 ConfigManager的属性
     * @param jsons 
     */
    static init(jsons: {}[]) {
        jsons.forEach(json => {
            for (const key in json) {
                const sheetJson = json[key];
                ConfigManager.Ins[key] = sheetJson;
            }
        });
    }
}
/**
 * 处理配置表的一些帮助函数
 */
class ConfigHelper {
    /**
     * 根据ID查找元素
     * @param list 
     * @param id 
     * @returns 
     */
    static byId<T>(list: T[], id: number): T {
        let find = list.find((item) => {
            return item['id'] == id;
        })
        return find;
    }
    /**
     * 最后一个元素
     * @param list 
     * @returns 
     */
    static lastItem<T>(list: T[]): T {
        return list[list.length - 1];
    }
    /**
     * 第一个元素
     * @param list 
     * @returns 
     */
    static firstItem<T>(list: T[]): T {
        return list[0];
    }
    /**
     * 在配置表中随机n条数据
     * @param list 
     * @param count 随机数量
     * @param repeat 是否重复（暂未实现）
     * @returns 
     */
    static random<T>(list: T[], count: number, repeat: boolean = true): T[] | T {
        if (count <= 0) {
            console.error(`count must be > 0 `)
            return [];
        }
        if (count == 1) {
            let ranIdx = Math.floor(Math.random() * list.length);
            return list[ranIdx];
        } else {
            let result: T[] = [];
            for (let i = 0; i < count; i++) {
                let ranIdx = Math.floor(Math.random() * list.length);
                let ranItem = list[ranIdx];
                result.push(ranItem)
            }
            return result;
        }
    }
}

let home_data = fs.readFileSync('./build/home.json', { encoding: 'utf-8' });
let home_json = JSON.parse(home_data);
let recipe_data = fs.readFileSync('./build/recipe.json', { encoding: 'utf-8' });
let recipe_json = JSON.parse(recipe_data);


ConfigManager.init([home_json, recipe_json]);

console.log(ConfigManager.Ins.offcial_food_display);

let lastitem = ConfigHelper.lastItem(ConfigManager.Ins.offcial_food_display)
console.log(lastitem.id);

let randomItems = ConfigHelper.random(ConfigManager.Ins.offcial_food_display, 5)
console.log(randomItems);

let findById1 = ConfigHelper.byId(ConfigManager.Ins.offcial_food_display, 1)
console.log(findById1);

